<template>
  <div v-if="type === 1">
    <div class="top drag">新的朋友</div>
    <el-scrollbar class="main-content" @click="showDeleteCard = false">
      <div
        v-for="item in newFriendList"
        :key="item.sendUserId"
        class="row-op-panel"
        @contextmenu="
          (e) => {
            rightClick(e, item)
          }
        "
        @click="details(item)"
      >
        <div class="avatar">
          <el-avatar
            :src="
              Tool.getAvatar(
                item.type === 'other'
                  ? item.contactApplyUserInfo.userId
                  : item.contactUserInfo.userId,
                item.type === 'other'
                  ? item.contactApplyUserInfo.avatar
                  : item.contactUserInfo.avatar,
                500
              )
            "
            size="large"
            shape="square"
          />
          <div class="info">
            <div>
              {{
                item.type === 'other'
                  ? item.contactApplyUserInfo.nickName
                  : item.contactUserInfo.nickName
              }}
            </div>
            <div style="color: #a6a6a6">{{ item.contactApply.applyMsg }}</div>
          </div>
        </div>
        <div>
          <span v-if="computedTime(item.applyTime)" class="expired">已过期</span>
          <span v-if="!computedTime(item.applyTime) && item.applyStatus === 1" class="expired"
            >已同意</span
          >
          <span
            v-if="!computedTime(item.applyTime) && item.applyStatus === 0 && item.type === 'me'"
            class="expired"
            >等待对方同意</span
          >
          <el-button
            v-if="!computedTime(item.applyTime) && item.applyStatus === 0 && item.type === 'other'"
            type="primary"
            @click.stop="acceptApply(item)"
            >接受
          </el-button>
        </div>
      </div>
    </el-scrollbar>
    <div v-if="showDeleteCard" class="delete-card" :style="[{ left: x + 'px', top: y + 'px' }]">
      <el-card class="card" @click.stop="deleteApplyInfo">
        <span>删除</span>
      </el-card>
    </div>
  </div>
  <div v-if="type === 2">
    <div class="top2 drag">
      <span class="iconfont icon-zuojiantou no-drag" @click="type = 1"></span>
    </div>
    <div class="main-content2" @click="showDeleteCardB = false">
      <div class="user">
        <div class="user-img">
          <div class="a">
            <el-avatar
              :size="60"
              :src="
                Tool.getAvatar(
                  selectedApplyInfo.type === 'other'
                    ? selectedApplyInfo.contactApplyUserInfo.userId
                    : selectedApplyInfo.contactUserInfo.userId,
                  selectedApplyInfo.type === 'other'
                    ? selectedApplyInfo.contactApplyUserInfo.avatar
                    : selectedApplyInfo.contactUserInfo.avatar,
                  500
                )
              "
              shape="square"
            />
          </div>
          <div class="b">
            <span>{{
              selectedApplyInfo.type === 'other'
                ? selectedApplyInfo.contactApplyUserInfo.nickName
                : selectedApplyInfo.contactUserInfo.nickName
            }}</span>
          </div>
        </div>
        <div
          v-if="selectedApplyInfo.type === 'other'"
          class="more2"
          @click.stop="
            (e) => {
              rightClickB(e)
            }
          "
        >
          <span class="iconfont icon-more"></span>
        </div>
      </div>
      <div class="verification-message">
        <span>{{ selectedApplyInfo.contactApplyUserInfo.nickName }}：</span
        ><span>{{ selectedApplyInfo.contactApply.applyMsg }}</span>
      </div>
      <div v-if="showDeleteCardB" class="delete-cardB" :style="[{ left: x + 'px', top: y + 'px' }]">
        <el-card class="card" @click.stop="">
          <span>加入黑名单</span>
        </el-card>
      </div>
      <el-divider />
      <div class="button">
        <span v-if="selectedApplyInfo.type === 'me'">等待验证</span>
        <el-button
          v-if="selectedApplyInfo.type === 'other'"
          type="primary"
          @click="showVerificationCardInfo = true"
          >前往验证</el-button
        >
      </div>
    </div>
  </div>
  <div v-if="showVerificationCardInfo" class="add-contact-card no-drag">
    <el-card class="add-contact-card-info">
      <div class="title">通过朋友验证</div>
      <div class="applyMsg">
        <div class="info">
          <div class="a">备注名</div>
          <div>
            <el-input v-model="userApplyVerifyInfo.noteName" />
          </div>
        </div>
        <!--        <div>-->
        <!--          <div>标签</div>-->
        <!--          <div><el-input v-model="addFriendApplyFormData.applyMsg"/></div>-->
        <!--        </div>-->
      </div>
      <div class="sweet-circle-authority">
        <div class="a">设置甜甜圈权限</div>
        <div class="b">
          <div class="c" style="cursor: pointer" @click="userApplyVerifyInfo.sweetCircleAuth = 1">
            <span style="color: #000000; font-size: 14px">聊天、甜甜圈</span
            ><span
              v-if="userApplyVerifyInfo.sweetCircleAuth === 1"
              class="iconfont icon-dui active"
            ></span>
          </div>
          <el-divider />
          <div class="c" style="cursor: pointer" @click="userApplyVerifyInfo.sweetCircleAuth = 2">
            <span style="color: #000000; font-size: 14px">仅聊天</span
            ><span
              v-if="userApplyVerifyInfo.sweetCircleAuth === 2"
              class="iconfont icon-dui active"
            ></span>
          </div>
        </div>
      </div>
      <div v-if="userApplyVerifyInfo.sweetCircleAuth === 1" class="sweet-circle-authority">
        <div class="a">甜甜圈和状态</div>
        <div class="b">
          <div class="c">
            <span style="color: #000000; font-size: 14px">不让他（她）看</span>
            <el-switch
              v-model="userApplyVerifyInfo.sweetCircleStatusA"
              :active-value="1"
              :inactive-value="0"
            />
          </div>
          <el-divider class="divider" />
          <div class="c">
            <span style="color: #000000; font-size: 14px">不看他</span>
            <el-switch
              v-model="userApplyVerifyInfo.sweetCircleStatusB"
              :active-value="1"
              :inactive-value="0"
            />
          </div>
        </div>
      </div>
      <div class="button">
        <el-button class="confirm" type="primary" @click="acceptApply(1)">确定</el-button>
        <el-button class="cancel" type="primary" @click="showVerificationCardInfo = false"
          >取消
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import Tool from '#/utils/Tool'
import { computed, ref } from 'vue'
import Api from '../../utils/Api'
import { useNewFriendStore } from '#/stores/NewFriendStore'
import { useContactInfoStore } from '#/stores/ContactInfoStore'
import { useUserInfoStore } from '#/stores/UserInfoStore'
import { ElMessage } from "element-plus";

const contactInfoStore = useContactInfoStore() // 存储联系人信息  用户的所有联系人
const userInfoStore = useUserInfoStore() // 登录用户存储信息
const newFriendStore = useNewFriendStore() // 新的朋友存储信息

const showDeleteCard = ref(false) // 是否显示 删除卡片  右击 联系人元素 显示 删除菜单
const showDeleteCardB = ref(false) // 是否显示 假如黑名单 菜单 卡片 （点击联系人 进入详情 右上角有个··· 点击它弹出菜单 加入黑名单）
const showVerificationCardInfo = ref(false) // 同意新朋友的验证卡片
const x = ref() // 删除卡片的 x 坐标
const y = ref() // 删除卡片的 y 坐标
const selectedApplyInfo = ref({}) // 选择的联系人申请信息
const type = ref(1)

const newFriendList = computed(() => {
  return newFriendStore.getNewFriend()
})
// 同意好友申请的请求数据
const userApplyVerifyInfo = ref({
  noteName: '', // 备注名
  sweetCircleAuth: 1, // 甜甜圈状态
  sweetCircleStatusA: 0, // 甜甜圈状态
  sweetCircleStatusB: 0 // 甜甜圈状态
})

const vh = ref(window.innerHeight) // 获取窗口高度
// const vh = ref(document.documentElement.clientHeight);
const vw = ref(window.innerWidth) // 获取窗口宽度
// 监听窗口变化
window.addEventListener('resize', () => {
  vh.value = window.innerHeight // 获取窗口高度
  vw.value = window.innerWidth // 获取窗口宽度
})
/**
 * window.addEventListener 是一个非常常用的方法，用于向窗口 (window) 对象添加事件监听器。窗口对象可以监听很多种类型的事件，这些事件大致可以分为几类：
 * 鼠标事件:
 * click：当用户点击鼠标按钮时触发。
 * dblclick：当用户双击鼠标按钮时触发。
 * mousedown：当用户按下鼠标按钮时触发。
 * mouseup：当用户释放鼠标按钮时触发。
 * mousemove：当鼠标移动时触发。
 * mouseover：当鼠标进入元素时触发。
 * mouseout：当鼠标离开元素时触发。
 * mouseenter：当鼠标进入元素时触发（不冒泡）。
 * mouseleave：当鼠标离开元素时触发（不冒泡）。
 * 键盘事件:
 * keydown：当用户按下键盘上的键时触发。
 * keyup：当用户释放键盘上的键时触发。
 * keypress：当用户按下并释放键盘上的键时触发。
 * 焦点事件:
 * focus：当元素获得焦点时触发。
 * blur：当元素失去焦点时触发。
 * 表单事件:
 * submit：当提交表单时触发。
 * reset：当重置表单时触发。
 * change：当表单控件的值改变时触发。
 * input：当输入字段的值发生变化时触发。
 * 滚动事件:
 * scroll：当文档滚动时触发。
 * 大小调整事件:
 * resize：当窗口被调整大小时触发。
 * 加载和卸载事件:
 * load：当文档完成加载时触发。
 * beforeunload：当文档即将卸载时触发。
 * unload：当文档正在卸载时触发。
 * 其他事件:
 * error：当错误发生时触发。
 * hashchange：当 URL 的哈希部分发生变化时触发。
 * message：当从另一个窗口发送消息时触发。
 * orientationchange：当设备方向改变时触发。
 * storage：当存储在另一个窗口中的数据发生变化时触发。
 */

/**
 * 计算申请时间 是否过期 7天
 * @param time
 * @returns {boolean}
 */
const computedTime = (time) => {
  // 获取当前时间戳
  const timestamp = Date.now()
  // 比较时间戳 是否大于七天的时间戳
  return timestamp > time + 7 * 24 * 60 * 60 * 1000
}

/**
 * 右击联系人 时触发
 * @param e
 * @param item
 */
const rightClick = (e, item) => {
  selectedApplyInfo.value = item // 设置选中的申请信息
  showDeleteCard.value = true // 显示删除卡片
  x.value = e.clientX + 5 // 设置删除卡片的 x 坐标
  y.value = e.clientY + 5 > vh.value - 40 ? vh.value - 45 : e.clientY + 5 // 设置删除卡片的 y 坐标  判断鼠标位置是否在指定范围内
}
/**
 * 右击··· 触发 加入黑名单
 * @param e
 */
const rightClickB = (e) => {
  showDeleteCardB.value = true
  x.value = e.clientX + 5
  y.value = e.clientY + 5
}

/**
 * 详情 申请详情
 * @param item
 */
const details = (item) => {
  if (item.applyStatus === 0) {
    if (!showDeleteCard.value) {
      type.value = 2
      selectedApplyInfo.value = item
    }
  }
}
/**
 * 删除申请信息
 */
const deleteApplyInfo = async () => {
  const res = await Api.deleteContactApply(
    selectedApplyInfo.value.contactApplyId,
    userInfoStore.getUserInfo().userId
  )
  if (res.code === 200) {
    ElMessage.success('删除成功')
    let newFriendApplyList = []
    for (let i = 0; i < res.data.length; i++) {

      // 遍历数组
      let info = res.data[i] // 获取元素
      let a = JSON.parse(info.applyContent) // 将json字符串转换为 对象
      let c = {
        // 创建对象
        applyTime: info.applyTime,
        applyStatus: info.applyStatus,
        contactApplyUserInfo: a.contactApplyUserInfo,
        contactApply: a.contactApply,
        contactUserInfo: a.contactUserInfo,
        type: a.type,
        contactApplyId: info.contactApplyId
      }
      newFriendApplyList.push(c) // 添加对象
    }
    newFriendStore.setNewFriend(newFriendApplyList) // 更新本地存储
    showDeleteCard.value = false
  }
}

/**
 * 接受申请，同意申请
 * @param item
 * @returns {Promise<void>}
 */
const acceptApply = async (item) => {
  if (item === 1) {
    // 经过验证后点击同意
    type.value = 1
    showVerificationCardInfo.value = false
    item = selectedApplyInfo.value
  }
  const userInfo = userInfoStore.getUserInfo()
  let contact = {
    userId: userInfo.userId,
    contactUserId: item.contactUserInfo.userId,
    contactUserSweetCircleId: item.contactUserInfo.userSweetCircleId,
    friendsCode: 1,
    avatar: item.contactUserInfo.avatar,
    nickName: item.contactUserInfo.nickName,
    joinType: item.contactUserInfo.joinType,
    sex: item.contactUserInfo.sex,
    personalSignature: item.contactUserInfo.personalSignature,
    addTime: Date.now(),
    areaName: item.contactUserInfo.areaName,
    noteName: userApplyVerifyInfo.value.noteName,
    sweetCircleAuth: userApplyVerifyInfo.value.sweetCircleAuth,
    sweetCircleStatusA: userApplyVerifyInfo.value.sweetCircleStatusA,
    sweetCircleStatusB: userApplyVerifyInfo.value.sweetCircleStatusB
  }
  let contact2 = {
    userId: item.contactUserInfo.userId,
    contactUserId: userInfo.userId,
    contactUserSweetCircleId: userInfo.userSweetCircleId,
    friendsCode: 1,
    avatar: userInfo.avatar,
    nickName: userInfo.nickName,
    joinType: userInfo.joinType,
    sex: userInfo.sex,
    personalSignature: userInfo.personalSignature,
    addTime: Date.now(),
    areaName: userInfo.areaName,
    noteName: '',
    sweetCircleAuth: 1,
    sweetCircleStatusA: 0,
    sweetCircleStatusB: 0
  }
  const res = await Api.acceptApply({
    userContactA: contact, // 我的好友
    userContactB: contact2
  })
  if (res.code === 200) {
    // 重新获取联系人列表
    contactInfoStore.setContactInfoList(res.data)
    // 修改新朋友的处理状态
    let newFriendList = newFriendStore.getNewFriend()
    newFriendList.forEach((item2) => {

      if (item2.contactApplyId === item.contactApplyId) {
        item2.applyStatus = 1
      }
    })
    newFriendStore.setNewFriend(newFriendList)
  }
}
</script>
<style lang="scss" scoped>
.top {
  height: 60px;
  border-bottom: 1px solid #dcdcdc;
  padding: 15px;
  font-size: 20px;
}

.top2 {
  height: 60px;
  padding: 15px;
}

.expired {
  color: #8c8c8c;
}

.main-content {
  height: calc(100vh - 60px);

  .row-op-panel {
    margin: 0 100px 0 100px;
    padding: 10px 0 10px 0;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #dcdcdc;

    .avatar {
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;

      .info {
        height: 40px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        align-items: start;
        margin-left: 10px;
        font-size: 13px;
        color: #000000;
      }
    }
  }
}

:deep(.el-button) {
  border-radius: 0;
}

.delete-card {
  position: absolute;

  .card {
    border-radius: 0;
    width: 80px;
    height: 40px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    user-select: none;

    &:hover {
      background: #eaeaea;
    }
  }
}

.delete-cardB {
  position: absolute;

  .card {
    padding: 13px;
    border-radius: 0;
    width: auto;
    height: 30px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    user-select: none;
    font-size: 12px;

    &:hover {
      background: #eaeaea;
    }
  }
}

.icon-zuojiantou {
  font-size: 25px;
  color: #8c8c8c;
  cursor: pointer;

  &:hover {
    color: #000000;
  }
}

.main-content2 {
  padding: 50px 120px 0 120px;
  height: calc(100vh - 60px);

  .user {
    width: 350px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: start;

    .user-img {
      display: flex;
      flex-direction: row;
      justify-content: start;
      align-items: start;

      .b {
        margin-left: 20px;
      }
    }

    .more2 {
      width: 25px;
      height: 25px;
      border-radius: 3px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 20px;

      &:hover {
        background-color: #e0e0e0;
      }
    }
  }

  .verification-message {
    margin-top: 10px;
    color: #8c8c8c;
    font-size: 13px;
  }
}

.button {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

.add-contact-card {
  user-select: none;
  width: 100%;
  height: 100%;
  float: left;
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-left: 15px;

  .el-card {
    border: 1px solid #dedede;
    border-radius: 0;
    // 取消阴影
    box-shadow: none;
  }

  .add-contact-card-info {
    width: 300px;
    height: auto;
    //display: flex;
    //flex-direction: column;
    //align-items: start;
    //justify-content: center;
    background: #ebebec;

    :deep(.el-card__body) {
      padding: 0 15px 15px 15px;
    }

    .title {
      font-size: 15px;
      display: flex;
      justify-content: center;
    }

    .applyMsg {
      width: 260px;

      :deep(.el-input__wrapper) {
        //border-radius: 2px;
        box-shadow: none;
      }
    }

    .a {
      color: #bbbbbb;
      font-size: 13px;
      margin: 10px 0 10px 0;
    }

    .sweet-circle-authority {
      .b {
        background: #ffffff;
        padding: 15px;

        .c {
          display: flex;
          flex-direction: row;
          justify-content: space-between;
        }
      }
    }

    .button {
      height: 50px;
      margin-top: 10px;
      display: flex;
      align-items: center;
      justify-content: center;

      .el-button {
        width: 100px;
      }

      .cancel {
        background-color: #dfdfe0;
        border: none;
        color: #07c160;

        &:hover {
          background-color: #c0c0c0;
        }
      }
    }
  }
}

.active {
  color: #07c160;
}

.divider {
  margin: 10px 0 10px 0;
}

.el-card__body {
  padding: 0;
}
</style>
